package com.service.zk;

import com.alibaba.fastjson2.JSON;
import com.bean.zk.Log;
import com.bean.zk.Power;
import com.dao.zk.LogDAO;
import com.dao.zk.PowerDAO;
import com.util.zk.TreeJsonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class PowerService {

    @Resource
    private PowerDAO powerDAO;
    @Resource
    private LogDAO logDAO;

    public List<Power> getAllPowers(String rid) {
//        转换
        List<Power> list = powerDAO.getPowersById(Integer.parseInt(rid));

        List<Power> treeJson = TreeJsonUtil.getTreeJson(powerDAO.getAllPowers(), list);
        return treeJson;
    }

    /**
     * 更新角色权限
     *
     * @param checkedList
     * @param rid
     * @param request
     */
    public void dealPower(Integer[] checkedList, String rid, HttpServletRequest request) {
//        父节点
        Integer[] fatherNode = new Integer[]{1, 5, 10, 13, 20, 26, 29};
//        前端传来的选中的权限
        List<Integer> newChecked = new ArrayList<Integer>();

//        排除父节点
        loop:
        for (Integer integer1 : checkedList) {
            for (Integer integer : fatherNode) {
                if (integer != integer1) {
                    continue;
                } else {
                    continue loop;
                }
            }
            newChecked.add(integer1);
        }


//        查询当前用户的权限
        List<Map<String, Object>> powerIds = powerDAO.getPowerIds(Integer.parseInt(rid));

//        转为list集合
        List<Integer> allpower = new ArrayList<Integer>();
        for (int i = 0; i < powerIds.size(); i++) {
            allpower.add((Integer) powerIds.get(i).get("power_id"));
        }
//日志
        Map<String, String> beforeData = new HashMap<String, String>();
        beforeData.put("power_id", allpower.toString());
        beforeData.put("rid", rid);
        Map<String, String> afterData = new HashMap<String, String>();
        afterData.put("power_id", newChecked.toString());
        afterData.put("rid", rid);
        Log log = new Log();
//        从session获取eid放入log中
        Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("user");
        Object eid = user.get("eid");
        log.setEid((Integer) eid);
        log.setRemark("更新角色权限");
        log.setBefore(JSON.toJSONString(beforeData));
        log.setAfter(JSON.toJSONString(afterData));
        log.setLtype("manage");
//        执行插入方法，添加一条日志记录
        logDAO.insert(log);

        updatePower(newChecked, allpower, rid);

    }

    public int updatePower(List<Integer> newChecked, List<Integer> allpower, String rid) {
        int effect = 0;
        int x = 0;
        //        得到变化的权限
        Set<Integer> difference = getIds(newChecked, allpower);

        for (Integer integer1 : difference) {
            for (Integer integer : newChecked) {
                //被选中的添加
                if (integer != null && integer1 != null && integer1 == integer) {
                    effect = powerDAO.insert(Integer.parseInt(rid), integer1);
                    x += effect;
                    break;
                }
                //被取消的删除
                if (integer1 != null) {
                    effect = powerDAO.delete(Integer.parseInt(rid), integer1);
                    x += effect;
                }

            }

        }
        if (x == difference.size()) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 数组比较
     *
     * @param a
     * @param b
     * @return
     */
    public Set<Integer> getIds(List<Integer> a, List<Integer> b) {
        Set<Integer> temp = new HashSet<Integer>();  //用来存放数组a中的元素
        for (int i = 0; i < a.size(); i++) {
            temp.add(a.get(i));   //把数组a中的元素放到Set中，可以去除重复的元素
        }

        for (int j = 0; j < b.size(); j++) {
            //把数组b中的元素添加到temp中
            //如果temp中已存在相同的元素，则temp.add（b[j]）返回false
            if (!temp.add(b.get(j)))
                temp.remove(b.get(j));
        }
        return temp;
    }

}
